<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * Content controller
 */
class Content extends Admin_Controller
{
    protected $permissionCreate = 'Buildings.Content.Create';
    protected $permissionDelete = 'Buildings.Content.Delete';
    protected $permissionEdit   = 'Buildings.Content.Edit';
    protected $permissionView   = 'Buildings.Content.View';

    private $photoType = 1;

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        
        $this->auth->restrict($this->permissionView);
        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/buildingsinfo_model', 'buildings_info_model');
        $this->load->model('buildings/buildingstag_model', 'buildings_tag_model');
        $this->load->model('buildings/photos_model');
        $this->load->model('area/area_model');
        $this->load->model('vendor/vendor_model');
        $this->load->model('category/category_model');
        $this->lang->load('buildings');
        
        $this->form_validation->set_error_delimiters("<span class='error'>", "</span>");
        
        Template::set_block('sub_nav', 'building/_sub_nav');

        Assets::add_module_js('buildings', 'buildings.js');
        Assets::add_css(array('plugins/select2/select2.min.css', 
                            'plugins/iCheck/all.css', 
                            'plugins/datepicker/datepicker3.css', 
                            'plugins/thickbox/thickbox.css'
                            ));
        Assets::add_js(array(Template::theme_url('plugins/select2/select2.full.min.js'), 
                            Template::theme_url('plugins/iCheck/icheck.min.js'), 
                            Template::theme_url('plugins/datepicker/bootstrap-datepicker.js'),
                            Template::theme_url('js/plupload-2.1.1/plupload.full.min.js'),
                            Template::theme_url('js/plupload-2.1.1/i18n/zh_CN.js'), 
                            Template::theme_url('js/qiniu.js'),
                            Template::theme_url('plugins/thickbox/thickbox3.js')
                            ));
    }

    /**
     * Display a list of Buildings data.
     *
     * @return void
     */
    public function index($filter = 'all', $offset = 0)
    {
        // Deleting anything?
        if (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);
            $checked = $this->input->post('checked');
            if (is_array($checked) && count($checked)) {

                // If any of the deletions fail, set the result to false, so
                // failure message is set if any of the attempts fail, not just
                // the last attempt

                $result = true;
                foreach ($checked as $pid) {
                    $deleted = $this->buildings_model->delete($pid);
                    if ($deleted == false) {
                        $result = false;
                    }
                }
                if ($result) {
                    Template::set_message(count($checked) . ' ' . lang('buildings_delete_success'), 'success');
                } else {
                    Template::set_message(lang('buildings_delete_failure') . $this->buildings_model->error, 'error');
                }
            }
        }

        $where = array('building.deleted'=>0);//array();
        $totalRows = $this->buildings_model->where($where)->count_all();
        // 搜索
        $q = $this->input->get('q');
        if (!empty($q)){
            $totalRows = $this->buildings_model->select()->where($where)->like('name', $q)->count_all();
            $records = $this->buildings_model->select()->where($where)->like('name', $q)->find_all();
        } else {
            $this->buildings_model->where($where);
        }

        $pagerUriSegment = 6;
        $pagerBaseUrl = site_url(SITE_AREA . '/content/buildings/index') . '/';
        
        $limit  = $this->settings_lib->item('site.list_limit') ?: 15;

        $this->load->library('pagination');
        $this->pager['base_url']    = $pagerBaseUrl.$filter."/";
        $this->pager['total_rows']  = $totalRows;
        $this->pager['per_page']    = $limit;
        $this->pager['uri_segment'] = $pagerUriSegment;

        $this->pagination->initialize($this->pager);
        $this->buildings_model->limit($limit, $offset);
        
        $records = !empty($records) ? $records : $this->buildings_model->find_all();

        Template::set('records', $records);

        Template::set('index_url', $pagerBaseUrl);
        Template::set('filter_type', $filter);
        Template::set('toolbar_title', lang('buildings_manage'));

        Template::render();
    }
    
    /**
     * Create a Buildings object.
     *
     * @return void
     */
    public function create()
    {
        $this->auth->restrict($this->permissionCreate);
        
        if (isset($_POST['save'])) {
            if ($insert_id = $this->save_buildings()) {
                log_activity($this->auth->user_id(), lang('buildings_act_create_record') . ': ' . $insert_id . ' : ' . $this->input->ip_address(), 'buildings');
                Template::set_message(lang('buildings_create_success'), 'success');

                redirect(SITE_AREA . '/content/buildings');
            }

            // Not validation error
            if ( ! empty($this->buildings_model->error)) {
                Template::set_message(lang('buildings_create_failure') . $this->buildings_model->error, 'error');
            }
        }
        //国家
        $country = $this->area_model->find_all_by("parent_id=0");
        Template::set('country', $country);
        // 省份
        $provinces = $this->area_model->provinces();
        Template::set('provinces', $provinces);
        // 开发商
        // Template::set('developers', $this->vendor_model->allDevelopers());
        // 集团
        Template::set('devGroups', $this->vendor_model->order_by('id','desc')->devGroups());
        // 楼盘分类
        Template::set('categories', $this->category_model->categories());

        Template::set('toolbar_title', lang('buildings_action_create'));

        Template::render();
    }
    /**
     * Allows editing of Buildings data.
     *
     * @return void
     */
    public function edit()
    {
        $id = $this->uri->segment(5);
        if (empty($id)) {
            Template::set_message(lang('buildings_invalid_id'), 'error');

            redirect(SITE_AREA . '/content/buildings');
        }
        
        if (isset($_POST['save'])) {
            $this->auth->restrict($this->permissionEdit);

            if ($this->save_buildings('update', $id)) {
                log_activity($this->auth->user_id(), lang('buildings_act_edit_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'buildings');
                Template::set_message(lang('buildings_edit_success'), 'success');
                redirect(SITE_AREA . '/content/buildings');
            }

            // Not validation error
            if ( ! empty($this->buildings_model->error)) {
                Template::set_message(lang('buildings_edit_failure') . $this->buildings_model->error, 'error');
            }
        }
        
        elseif (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);

            if ($this->buildings_model->delete($id)) {
                log_activity($this->auth->user_id(), lang('buildings_act_delete_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'buildings');
                Template::set_message(lang('buildings_delete_success'), 'success');

                redirect(SITE_AREA . '/content/buildings');
            }

            Template::set_message(lang('buildings_delete_failure') . $this->buildings_model->error, 'error');
        }
        
        $building = $this->buildings_model->find($id);
        //获取当前楼盘所在国家
        $tmp = $this->area_model->find($building->province_id);
        $cur_country = $this->area_model->find($tmp->parent_id);
        $building->country_id = $cur_country->area_id;
        //国家
        $country = $this->area_model->find_all_by("parent_id=0");
        Template::set('country', $country);
        // 省份
        $provinces = $this->area_model->provinces($building->country_id);
        Template::set('provinces', $provinces);
        // 城市
        $province_id = $building->province_id;
        Template::set('cities', empty($province_id) ? [] : $this->area_model->cities($province_id));
        // 区县
        $city_id = $building->city_id;
        Template::set('districts', empty($city_id) ? [] : $this->area_model->districts($city_id));
        // 集团
        if ($building->developer_id) {
            $developer = $this->vendor_model->find($building->developer_id);
            $building->group_id = $developer->parent_id;
            // 开发商
            Template::set('developers', $this->vendor_model->allDevelopersForGroupId($developer->parent_id));
        }
        
        $devGroups = $this->vendor_model->devGroups();
        Template::set('devGroups', $devGroups);
        
        // 楼盘分类
        $categories = $this->category_model->categories();
        // 楼盘标签
        $buildingTags = $this->buildings_tag_model->where('building_id', $id)->find_all();

        if (is_array($buildingTags)) {
            foreach ($buildingTags as $key => $val) {
                // 分类标签
                if ($val->type == '3') {
                    foreach ($categories as $k => $v) {
                        if ($val->tag_id == $v->tag_id) $categories[$k]->selected = 1;
                    }
                }
            }
        }
        Template::set('categories', $categories);
        // 普通标签
        $tags = $this->buildings_tag_model->tags($id, 1);
        Template::set('tags', $tags?:[]);
        // 特色标签
        $stags = $this->buildings_tag_model->tags($id, 2);
        Template::set('stags', $stags?:[]);
        // 缩略图
        $thumbImg = $this->photos_model->find_by(array('type'=>$this->photoType, 'sub_type'=>1, 'target_id'=>$id));
        Template::set('thumbImg', $thumbImg);
        
        Template::set('buildings', $building);
        Template::set('buildingsInfoData', $this->buildings_info_model->find_by('building_id', $id));

        Template::set('toolbar_title', lang('buildings_edit_heading'));
        Template::render();
    }

    //--------------------------------------------------------------------------
    // !PRIVATE METHODS
    //--------------------------------------------------------------------------

    /**
     * Save the data.
     *
     * @param string $type Either 'insert' or 'update'.
     * @param int    $id   The ID of the record to update, ignored on inserts.
     *
     * @return boolean|integer An ID for successful inserts, true for successful
     * updates, else false.
     */
    private function save_buildings($type = 'insert', $id = 0)
    {
        if ($type == 'update') {
            $_POST['id'] = $id;
        }

        // Validate the data
        $this->form_validation->set_rules($this->buildings_model->get_validation_rules());
        if ($this->form_validation->run() === false) {
            return false;
        }
        // print_r($this->input->post());
        // exit;
        // Make sure we only pass in the fields we want
        $post = $this->input->post();
        $data = $this->buildings_model->prep_data($post);
        $infoData = $this->buildings_info_model->prep_data($post);
        $building_thumb_url = $post['building_thumb_url'];
        $tags = $post['tags']; // 普通标签
        $stags = $post['s_tags']; // 特色标签

        // Additional handling for default values should be added below,
        // or in the model's prep_data() method
    
        if (!isset($infoData['phone_switch'])) $infoData['phone_switch'] = 0;
        if (!isset($infoData['yuyue_switch'])) $infoData['yuyue_switch'] = 0;
        if (!isset($infoData['hx_switch'])) $infoData['hx_switch'] = 0;
        if (!isset($infoData['chat_switch'])) $infoData['chat_switch'] = 0;
        if (!isset($infoData['building_switch'])) $infoData['building_switch'] = 0;
        if (!isset($infoData['lingxi_switch'])) $infoData['lingxi_switch'] = 0;

        $return = false;
        if ($type == 'insert') {
            $id = $this->buildings_model->insert($data);

            if (is_numeric($id)) {
                // 写入楼盘信息表
                $infoData['building_id'] = $id;
                $infoId = $this->buildings_info_model->insert($infoData);
                // 楼盘标签表(包括：分类、特色标签、普通标签)
                $this->buildings_tag_model->addCategories($id, $post['category']);
                if (is_array($tags)) $this->buildings_tag_model->addTags($id, 1, $tags); // 普通标签
                if (is_array($stags)) $this->buildings_tag_model->addTags($id, 2, $stags); // 特色标签
                // 封面图
                $this->photos_model->insert(array('url'=>$building_thumb_url, 'type'=>$this->photoType, 'sub_type'=>1, 'target_id'=>$id));
                if (is_numeric($infoId)) $return = $id;
            }
        } elseif ($type == 'update') {
            $return = $this->buildings_model->update($id, $data);
            // 更新楼盘信息表
            $this->buildings_info_model->update_where('building_id', $id, $infoData);
            // 更新楼盘标签表(包括：分类、特色标签、普通标签)
            $this->buildings_tag_model->updateCategories($id, $post['category']);
            if (is_array($tags)) $this->buildings_tag_model->addTags($id, 1, $tags); // 普通标签
            if (empty($tags)) $this->buildings_tag_model->delete_where("building_id=$id"); // 普通标签
            if (is_array($stags)) $this->buildings_tag_model->addTags($id, 2, $stags); // 特色标签
            // 更新封面图
            if (!empty($building_thumb_url)) {
                $this->photos_model->update(array('type'=>$this->photoType, 'sub_type'=>1, 'target_id'=>$id), array('url'=>$building_thumb_url));
            }
        }

        return $return;
    }

    /**
     * 获取经纬度
     * @author fengchen@usuretech.com
     * @createtime 2016.3.31
     */
    public function getlocation()
    {   
        $get = $this->input->get();
        $address = $get["address"];
        $url="http://api.map.baidu.com/geocoder/v2/?address=".$address."&output=json&ak=8526cdc9eaa7faa35706d8d0fe54528d";
    
        $curl = curl_init();
        curl_setopt ($curl, CURLOPT_URL, $url);
        curl_setopt ($curl, CURLOPT_HEADER,false);
        curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($curl, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
        curl_setopt ($curl, CURLOPT_TIMEOUT,5);
        $data = curl_exec($curl);
        curl_close ($curl);
    
        $result=json_decode($data,true);
        if($result["result"]["location"]["lat"]!=""){
            $msg = "经纬度获取成功 （地址类型:".$result["result"]["level"]."）";
            $arr["lat"]=$result["result"]["location"]["lat"];
            $arr["lng"]=$result["result"]["location"]["lng"];
            echo json_encode(array('status' => '1', 'msg' => $msg, 'arr' => $arr));
        }else{
            $msg = "经纬度获取失败，请确认你的输入后重新获取!";
            echo json_encode(array('status' => '2', 'msg' => $msg, 'arr' => $result));
        }
    }
    /**
     * 获取经纬度新(因旧接口调取上海经纬度出bug)
     * @author fengchen@usuretech.com
     * @createtime 2016.11.7
     */
    public function getLocationNew(){
        $this->load->library( 'curl');
        $get = $this->input->get();
        $address = $get["address"];
        $getData['address'] = $address;
        $getData['output'] = 'json';
        $getData['ak'] = '8526cdc9eaa7faa35706d8d0fe54528d';

        $get_url = 'http://api.map.baidu.com/geocoder/v2/?'.http_build_query($getData, NULL, '&');
        $returnStr = $this->curl->_simple_call('get',$get_url);
        $returnData = json_decode($returnStr, true);
        if($returnData["result"]["location"]["lat"]!=""){
            $msg = "经纬度获取成功 （地址类型:".$returnData["result"]["level"]."）";
            $arr["lat"]=$returnData["result"]["location"]["lat"];
            $arr["lng"]=$returnData["result"]["location"]["lng"];
            echo json_encode(array('status' => '1', 'msg' => $msg, 'arr' => $arr));
        }else{
            $msg = "经纬度获取失败，请确认你的输入后重新获取!";
            echo json_encode(array('status' => '2', 'msg' => $msg, 'arr' => $returnData));
        }
    }
}